package com.health.mapp.impl;



import java.text.ParseException;
import java.text.SimpleDateFormat;

import org.apache.log4j.Logger;

import com.aliyun.oss.ClientException;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.sts.model.v20150401.AssumeRoleRequest;
import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse;
import com.health.commons.PropertiesService;
import com.health.mapp.bean.GetPersonalAccessKeyReq;
import com.health.mapp.bean.GetPersonalAccessKeyResp;
import com.health.mapp.bean.Header;
import com.health.mapp.utils.ResultCode;
import com.health.mapp.utils.StringUtils;

/**
 * 获取token
 * @author Administrator
 *
 */
public class GetPersonalAccessKeyImpl implements ActionInterface {

	private static Logger logger = Logger.getLogger(GetPersonalAccessKeyImpl.class);


	@Override
	public GetPersonalAccessKeyResp execute(Header header, Object reqBean)  {
		GetPersonalAccessKeyReq req = (GetPersonalAccessKeyReq) reqBean;
		GetPersonalAccessKeyResp _resp = new GetPersonalAccessKeyResp();
		

		  String accessKeyId = PropertiesService.getString("1oss.accessKeyId").trim();
		  String accessKeySecret = PropertiesService.getString("1oss.accessKeySecret").trim();
		  String  roleArn = PropertiesService.getString("1oss.roleReadWrite").trim();
		  String oper = 
		          "                \"oss:GetBucket\", \n" +
		          "                \"oss:GetObject\", \n" +
		          "                \"oss:PutObject\" \n";
		 
		 String roleSessionName = String.valueOf(req.getMemberId());

		    String policy = "{\n" +
      "    \"Version\": \"1\", \n" +
      "    \"Statement\": [\n" +
      "        {\n" +
      "            \"Action\": [\n" +oper  +
      "            ], \n" +
      "            \"Resource\": [\n" +
      "                \"acs:oss:*:*:app-server\", \n" +
      "                \"acs:oss:*:*:app-server/*\" \n" +
      
      "            ], \n" +
      "            \"Effect\": \"Allow\"\n" +
      "        }\n" +
      "    ]\n" +
      "}";
		    ProtocolType protocolType = ProtocolType.HTTPS;

		    try {
		      final AssumeRoleResponse response = assumeRole(accessKeyId, accessKeySecret,
		              roleArn, roleSessionName, policy, protocolType);
		      long expiration=stringDateToLong(response.getCredentials().getExpiration());
		      _resp.setAccessTime(StringUtils.getSysTimeYYMMDDHHMMSS());
		      _resp.setAccessId(response.getCredentials().getAccessKeyId());
		      _resp.setAccessSecret(response.getCredentials().getAccessKeySecret());
		      _resp.setToken(response.getCredentials().getSecurityToken());
		      _resp.setExpiration(expiration);
		      _resp.setCredentials(response.getCredentials());
		      
		      
		      _resp.setCredentials(response.getCredentials());
		      logger.debug("Token explain");
		      logger.debug("Expiration: " + response.getCredentials().getExpiration());
		      logger.debug("Access Key Id: " + response.getCredentials().getAccessKeyId());
		      logger.debug("Access Key Secret: " + response.getCredentials().getAccessKeySecret());
		      logger.debug("Security Token: " + response.getCredentials().getSecurityToken());
		    } catch (ClientException e) {
		    	logger.debug("Failed to get a federation token.");
		    	_resp.setErrorCode(ResultCode.OSS_TOKEN_CONNECT_ERROR);
		    	_resp.setErrorMsg(ResultCode.OSS_TOKEN_CONNECT_ERROR_NOTE);
		    } catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
		
		    }
		    
		    return _resp;
	}

	private long stringDateToLong(String dateString) throws ParseException
	{
		String dateFormatString=dateString.replace("T", " ").replace("Z", "");
		SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		java.util.Date date=format.parse(dateFormatString);
		
		return date.getTime();
		
	}
	static AssumeRoleResponse assumeRole(String accessKeyId,
			String accessKeySecret, String roleArn, String roleSessionName,
			String policy, ProtocolType protocolType) throws Exception {
			IClientProfile profile = DefaultProfile.getProfile(
					PropertiesService.getString("1oss.region").trim(), accessKeyId, accessKeySecret);
			DefaultAcsClient client = new DefaultAcsClient(profile);
			final AssumeRoleRequest request = new AssumeRoleRequest();
			request.setVersion(PropertiesService.getString("1oss.stsApiVersion").trim());
			request.setMethod(MethodType.POST);
			request.setProtocol(protocolType);
			request.setDurationSeconds((long) PropertiesService.getInteger("1oss.tokenLiveSecond",3600));
			request.setRoleArn(roleArn);
			request.setRoleSessionName("hiroad"+roleSessionName);
			request.setPolicy(policy);
			AssumeRoleResponse response =  client.getAcsResponse(request);
			return response;
		
	}
	
}